<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card class="box-card">
        <el-alert
         title="注意: 只允许为三级分类设置相关参数!"
         type="warning" show-icon :closable="false">
        </el-alert>
        <div style="margin: 15px 0">
          选择商品分类:
          <el-cascader
          v-model="cascateValue"
          :options="CateList"
          :props="PropsList"
          @change="cascatehandleChange" size="mini"></el-cascader>
        </div>
        <el-tabs v-model="activeName" @tab-click="TabshandleClick">
            <!-- 动态参数的面板 -->
          <el-tab-pane label="动态参数" name="many">
            <el-button @click="addParamsdialogVisible = true" :disabled="isBtnDisabled" type="primary">添加参数</el-button>
            <el-table border stripe :data="cascateList">
              <el-table-column type="expand">
                <template slot-scope="scope">
                <el-tag :key="index" v-for="(tag, index) in scope.row.attr_vals" @close="InputClose(scope.row, index)" closable>{{tag}}</el-tag>
                <el-input class="input-new-tag w" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="showeidtParams(scope.row)" type="primary" icon="el-icon-edit" size="mini">修改</el-button>
                  <el-button @click="delParams(scope.row)" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
            <!-- /动态参数的面板 -->
            <!-- 静态属性的面板 -->
          <el-tab-pane label="静态属性" name="only">
            <el-button @click="addParamsdialogVisible = true" :disabled="isBtnDisabled" type="primary">动态属性</el-button>
             <el-table border stripe :data="Onlytable">
              <el-table-column type="expand">
                <template slot-scope="scope">
                <el-tag :key="index" v-for="(tag, index) in scope.row.attr_vals" @close="InputClose(scope.row, index)" closable>{{tag}}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                @blur="handleInputConfirm(scope.row)"></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button @click="showeidtParams(scope.row)" type="primary" icon="el-icon-edit" size="mini">修改</el-button>
                  <el-button @click="delcateParams(scope.row)"  type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
            <!-- /静态属性的面板 -->
        </el-tabs>
      </el-card>
      <!-- 添加参数对话框 -->
 <el-dialog
  :title="'添加'+paramsText"
  :visible.sync="addParamsdialogVisible"
  width="30%"
  @close="addParamsClose">
  <el-form ref="AddparamsRef" :model="addparamsForm" label-width="80px"
  :rules="addParamsReles">
    <el-form-item :label="paramsText" prop="attr_name">
      <el-input v-model="addparamsForm.attr_name"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addParamsdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveParams">确 定</el-button>
  </span>
  </el-dialog>
 <el-dialog
  :title="'修改'+paramsText"
  :visible.sync="editParamsdialogVisible"
  width="30%"
  @close="editParamsClose">
  <el-form ref="EditparamsRef" :model="editcateParams" label-width="80px"
  :rules="editParamsReles">
    <el-form-item :label="paramsText" prop="attr_name">
      <el-input v-model="editcateParams.attr_name"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editParamsdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveeditParams">确 定</el-button>
  </span>
  </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      CateList: [],
      //  级联选择器的数据绑定
      cascateValue: [],
      PropsList: {
        // children: 'children',
        //  级联选择器发生变化 保存的数据
        value: 'cat_id',
        label: 'cat_name',
        expandTrigger: 'hover'
      },
      activeName: 'many',
      //  动态参数
      cascateList: [],
      //  静态属性
      Onlytable: [],
      addParamsdialogVisible: false,
      addparamsForm: {
        attr_name: ''
      },
      addParamsReles: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 7 个字符', trigger: 'blur' }]
      },
      editParamsdialogVisible: false,
      // 点击修改时获取的数据
      editcateParams: {},
      editParamsReles: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 7 个字符', trigger: 'blur' }]
      }
    }
  },

  created () {
    this.getCateList()
  },
  computed: {
    //  控制按钮禁用状态
    isBtnDisabled () {
      return this.cascateValue.length !== 3
    },
    //  分类Id
    cateId () {
      if (this.cascateValue.length === 3) {
        return this.cascateValue[2]
      }
      return null
    },
    //  弹窗标题
    paramsText () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.CateList = res.data
    },
    //  级联选择器发生变化
    cascatehandleChange () {
      this.getCateParams()
    },
    TabshandleClick () {
      this.getCateParams()
    },
    //  渲染页面函数请求
    async getCateParams () {
      //  数组的长度不为3 就清空 只能选择3级
      if (this.cascateValue.length !== 3) {
        this.cascateValue = []
        this.cascateList = []
        this.Onlytable = []
      }
      const { data: res } = await this.axios.get(`categories/${
          this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      // console.log(res.data)
      if (res.meta.status !== 200) return this.$message.error('数据获取失败')
      //  将res.data进行循环 将里面的attr_vals从字符串转换为数组
      res.data.forEach(item => {
        //  判断空字符串就返回空数组
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.cascateList = res.data
      }
      this.Onlytable = res.data
    },
    //  添加参数提交
    saveParams () {
      this.$refs.AddparamsRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.axios.post('categories/' + this.cateId + '/attributes', {
          attr_name: this.addparamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.getCateParams()
        this.addParamsdialogVisible = false
        this.$message.success('添加成功')
      })
    },
    addParamsClose () {
      this.$refs.AddparamsRef.resetFields()
    },
    //  删除动态参数功能
    async delParams (row) {
      const id = row.attr_id
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.axios.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getCateParams()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    //  删除静态参数
    async delcateParams (row) {
      const id = row.attr_id
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.axios.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getCateParams()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    //  修改功能
    showeidtParams (row) {
      this.editParamsdialogVisible = true
      this.editcateParams = JSON.parse(JSON.stringify(row))
    },
    async saveeditParams () {
      const id = this.editcateParams.attr_id
      this.$refs.EditparamsRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.axios.put(`categories/${this.cateId}/attributes/${id}`, {
          attr_name: this.editcateParams.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.editParamsdialogVisible = false
        this.getCateParams()
        this.$message.success('修改成功')
      })
    },
    //  关闭表单重置
    editParamsClose () {
      this.$refs.EditparamsRef.resetFields()
    },
    //  敲回车或失去焦点
    async handleInputConfirm (row) {
      if (row.inputValue.trim() === '') {
        row.inputVisible = false
        return
      }
      // row.inputValue = ''
      row.attr_vals.push(row.inputValue)
      const { data: res } = await this.axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')//  字符串
      })
      if (res.meta.status !== 200) return this.$message.error('数据更新失败')
      row.inputValue = ' '
      row.inputVisible = false
      // this.getCateParams()
      this.$message.success('数据更新成功')
    },
    //  显示输入框
    showInput (row) {
      row.inputVisible = true
      //  数据驱动 是同步执行 页面更新 异步执行 （先执行同步）
      //  组件没有创建
      this.$nextTick(_ => {
        //  1.第一个refs先获取到 el-input <template><ref='input'/></template>
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //  删除标签操作
    async InputClose (row, i) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('删除更新失败')
      // this.getCateParams()
      this.$message.success('删除更新成功')
    }
  }
}
</script>

<style scoped lang='less'>
.w {
  width: 90px;
}
</style>
